/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"bufio"
	"encoding/hex"
	"fullerene/service"
	"log"
	"net"
	"os"
	"time"

	"github.com/spf13/cobra"
	"github.com/vmihailenco/msgpack"
)

// loginCmd represents the login command
var loginCmd = &cobra.Command{
	Use:   "login",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
		login()
	},
}

func init() {
	clientCmd.AddCommand(loginCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// loginCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// loginCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func login() {
	conn, err := net.Dial("tcp", "localhost:8888")
	if err != nil {
		log.Fatal(err)
	}
	data, err := service.NewMessage().SetType(service.Login).SetPayload(map[string]interface{}{
		"name": "test",
		"pwd":  "123456",
	}).Bytes()
	if err != nil {
		log.Fatal(err)
	}
	log.Println("send:", hex.EncodeToString(data))
	_, err = conn.Write(data)
	if err != nil {
		log.Fatal(err)
	}
	go func() {
		for {
			var data = make([]byte, 1024)
			n, err := conn.Read(data)
			if err != nil {
				log.Fatal(err)
			}
			data = data[:n]
			if len(data) == 0 {
				continue
			}
			if data[0] == byte(service.Pong) {
				continue
			}
			var m string
			if data[1] <= 0x7f {
				msgpack.Unmarshal(data[2:], &m)
				log.Println("recv:", hex.EncodeToString(data[2:]), m)
				continue
			}
			if data[2] <= 0x7f {
				msgpack.Unmarshal(data[3:], &m)
				log.Println("recv:", hex.EncodeToString(data[3:]), m)
				continue
			}
			if data[3] <= 0x7f {
				msgpack.Unmarshal(data[4:], &m)
				log.Println("recv:", hex.EncodeToString(data[4:]), m)
				continue
			}
			msgpack.Unmarshal(data[5:], &m)
			log.Println("recv:", hex.EncodeToString(data[5:]), m)
			continue
		}
	}()
	go func() {
		for {
			time.Sleep(time.Second)
			msg, err := service.NewMessage().SetType(service.Ping).SetPayload("ping").Bytes()
			if err != nil {
				log.Println(err)
			}
			conn.Write(msg)
		}
	}()
	input := bufio.NewReader(os.Stdin)
	for {
		line, err := input.ReadString('\n')
		if err != nil {
			log.Fatal(err)
		}
		line = line[:len(line)-1]
		if len(line) <= 0 {
			continue
		}
		msg, err := service.NewMessage().SetType(service.ChatText).SetPayload(line).Bytes()
		if err != nil {
			log.Println(err)
		}
		_, err = conn.Write(msg)
		if err != nil {
			panic(err)
		}
	}
}
